import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  // 标签列表
  public tagList:{id:number,name:string}[];
  // 联系人列表
  public contactList:{
    id:number,
    name:string,
    email:string,
    tel:string,
    tagId:number
  }[]
  
  constructor() {
    // 获取本地存储中的tagList
    this.tagList=this.getTagList();
    this.contactList=this.getContactList();
  }

  // 从本地存储中获取联系人列表
  getContactList():Array<{id:number,name:string,tel:string,email:string,tagId:number}>{
    let list=JSON.parse(localStorage.getItem('contactList'))||[];  
    return list;
  }

  // 新增联系人
  contactAdd(conact:{name:string,email:string,tel:string,tagId:number}):void{
    const last=this.contactList[this.contactList.length-1];
    const lastId=last?last.id+1:1;
    // this.contactList.push({
    //   id:lastId,
    //   name:'测试',
    //   tel:'18629688888',
    //   email:'mail@qq.com',
    //   tagId:1
    // });
    this.contactList.push(Object.assign({id:lastId},conact));
    localStorage.setItem('contactList',JSON.stringify(this.contactList));
  }

  // 删除联系人
  contactDel(id):void{
    const index=this.contactList.findIndex(item=>item.id==id);
    this.contactList.splice(index,1);
    localStorage.setItem('contactList',JSON.stringify(this.contactList));
  }

  // 编辑联系人
  contactEdit(contact:{id:number,name:string,email:string,tel:string,tagId:number}){
     const index=this.contactList.findIndex(item=>item.id==contact.id);
     this.contactList[index]=contact;
     localStorage.setItem('contactList',JSON.stringify(this.contactList));
  }



  // 从本地存储中读取tagList
  getTagList(): Array<{ id: number, name: string }> {
    let list = JSON.parse(localStorage.getItem('tagList')) || [];
    return list;
  }

  // 新增标签
  tagAdd(tagObj:{name:string}):void {
    let arr = this.tagList;
    const last=arr[arr.length-1];
    const lastId=last?last.id+1:1;
    arr.push({id:lastId,name:tagObj.name});
    localStorage.setItem('tagList',JSON.stringify(arr));
  }

  
  // 编辑标签
  tagEdit(id:number,tagName:string):void{
    let arr=this.tagList;
    arr.forEach((item,index)=>{
        if(item.id==id){
           arr[index].name=tagName; 
        }
    });
    localStorage.setItem('tagList',JSON.stringify(arr));
  }

  // 删除标签
  tagDel(id:number):void{
    const arr=this.tagList;
    const index=arr.findIndex(item=>item.id==id);
    arr.splice(index,1);
    localStorage.setItem('tagList',JSON.stringify(arr));
  }
}
